# 15. 罗马数字转整数.py
import math
from typing import List
class Solution:
    def romanToInt(self, s: str) -> int:
        map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        res = 0
        length = len(s)
        if length == 1:
            res = map[s]
            return res
        i = 0
        while i < length-1:
            if map[s[i]] < map[s[i+1]]:
                res += map[s[i+1]] - map[s[i]]
                i += 2
            else:
                res += map[s[i]]
                i += 1
        if i == length-1:
            if map[s[i-1]] >= map[s[i]]:
                res += map[s[i]]
        return res

class Solution2:
    def romanToInt(self, s: str) -> int:
        map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        res = 0
        length = len(s)
        if length == 1:
            res = map[s]
            return res
        i = 0
        # 一个字符一个字符来处理
        while i < length-1:
            if map[s[i]] < map[s[i+1]]:
                res -= map[s[i]]
                i += 1
            else:
                res += map[s[i]]
                i += 1
        # 处理最后一个字符，一定是直接加上
        res += map[s[i]]
        return res